package com.enhe.gck.com.oracle;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.CarbonEnumKeyValue;
import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.item.*;
import com.enhe.gck.pojo.Customer;
import com.enhe.gck.pojo.ErrorRecord;
import com.enhe.gck.pojo.Goods;
import com.enhe.gck.pojo.MaterialAll;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.ProRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Verb;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;

@Slf4j
@Repository(value = "MY20240516S1")
public class OracleService {

    @Resource
    private HMACExampleUtils hmacExampleUtils;

    /**
     * 获取客户
     */
    public boolean getCompany(OracleEntity.Parameter info) {
        info.setSiCode(PublicConstant.subsidiaryNo);
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.abutmentCompanyUrl,JSON.toJSONString(info));
        if(r.isOk()){
            List<OracleEntity.Custom> list=JSON.parseArray(JSON.toJSONString(r.getData().get("data")), OracleEntity.Custom.class);
            if(list!=null){
                Customer customer=new Customer();
                list.forEach(x->{
                    customer.setType(String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_经销商_jxs));
                    customer.setName(x.getSubsidiaryName());
                    customer.setIsDelete(String.valueOf(x.getIsInactive().equals("T")?CarbonEnumKeyValue.是否_是_s:CarbonEnumKeyValue.是否_否_f));
                    customer.setCustomerId(x.getCustomerId());
                    customer.setIsRetail(false);
                    customer.setCustomerName(x.getCustomerName());
                    saveCompany(customer);
                });
            }
        }
        saveErrorRecord(null,String.valueOf(CarbonEnumKeyValue.调用接口_获取销售商_hqxss),JSON.toJSONString(info),r);
        return r.isOk();
    }
    /**
     * 供应商接口
     */
    public boolean getSupplier(OracleEntity.Parameter info) {
        info.setSiCode(PublicConstant.subsidiaryNo);
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.abutmentSupplierUrl,  JSON.toJSONString(info));
        if(r.isOk()){
            List<OracleEntity.Supplier> list= JSON.parseArray(JSON.toJSONString(r.getData().get("data")), OracleEntity.Supplier.class);
            if(list!=null){
                Customer customer=new Customer();
                list.forEach(x->{
                    customer.setType(String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_供货商_ghs));
                    customer.setName(x.getVendorName());
                    customer.setIsDelete(String.valueOf(x.getIsInactive().equals("T")?CarbonEnumKeyValue.是否_是_s:CarbonEnumKeyValue.是否_否_f));
                    customer.setCustomerId(x.getVendorId());
                    customer.setCustomerName(x.getVendorNum());
                    saveCompany(customer);
                });
            }
        }
        saveErrorRecord(null,String.valueOf(CarbonEnumKeyValue.调用接口_获取供应商_hqgys),JSON.toJSONString(info),r);
        return r.isOk();
    }
    public void saveCompany(Customer info) {
        List<String> oldId = CarbonPanel
                .getRecordQueryFactory(CarbonBaseConstant.客户管理_khgl)
                .getProConJunctionFactory()
                .addEqual(CustomerHWANE16644Item.基本属性组_客户类型,Long.valueOf(info.getType()))
                .addEqual(CustomerHWANE16644Item.基本属性组_客户主键,info.getCustomerId())
                .goBack().queryCodes();
        log.info("记录主键：{}", oldId);
        if(oldId==null|| oldId.isEmpty()){
            CarbonPanel.getRecordIntegration(CarbonBaseConstant.客户管理_khgl).integrate(info);
        }else {
            CarbonPanel.getFGRecordBuilder(CarbonBaseConstant.客户管理_khgl,oldId.get(0))
                    .putAttribute(CustomerHWANE16644Item.基本属性组_客户编码,info.getCustomerName())
                    .putAttribute(CustomerHWANE16644Item.基本属性组_客户名称,info.getName())
                    .putAttribute(CustomerHWANE16644Item.基本属性组_是否删除,info.getIsDelete()).integrate();
        }
    }

    /**
     * 物料信息
     */
    public boolean geMaterial(OracleEntity.Parameter info) {
        info.setSiCode(PublicConstant.subsidiaryNo);
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.abutmentMaterialUrl, JSON.toJSONString(info));
        if(r.isOk()){
            List<MaterialAll> list=JSON.parseArray(JSON.toJSONString(r.getData().get("data")), MaterialAll.class);
            if(list!=null){
                list.forEach(x->{
                    x.setFlagInactive(x.getIsInactive().equals("T"));
                    saveMaterial(x);
                });
            }
        }
        saveErrorRecord(null,String.valueOf(CarbonEnumKeyValue.调用接口_获取物料信息_hqwlxx),JSON.toJSONString(info),r);
        return r.isOk();
    }
    public void saveMaterial(MaterialAll info) {
        MaterialAll materialAll=CarbonPanel.getRecordDiscover(CarbonBaseConstant.甲骨文物料_jgwwl).getRecordBean(info.getRecordCode(),MaterialAll.class,1);
        if(materialAll!=null){
            info.setId(materialAll.getId());
            CarbonPanel.getRecordIntegration(CarbonBaseConstant.甲骨文物料_jgwwl).integrate(info);
        }else {
            CarbonPanel.getRecordIntegration(CarbonBaseConstant.甲骨文物料_jgwwl).integrate(info);
        }
    }
    /**
     * 添加销售发货
     */
    public boolean saveOrder(List<OracleEntity.Order> list, boolean saveErrorRecord, boolean sync) {
        log.info("====获取到的推送销售发货单数据===={}",JSON.toJSONString(list));
        for (OracleEntity.Order order : list) {
            order.setSubsidiaryNo(PublicConstant.subsidiaryNo);
        }
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.pushSaleLade, JSON.toJSONString(list));

        if(sync&&r.isOk()){
            for (OracleEntity.Order info : list) {
                flagSyncTrue(CarbonBaseConstant.订单记录_ddjl,OrderHWANE16677Item.基本属性组_是否同步,info.getEhId());
            }
        }
        if(saveErrorRecord){
            saveErrorRecord(!list.isEmpty()?list.get(0).getDocumentNo():null,String.valueOf(CarbonEnumKeyValue.调用接口_发送销售发货_fsxsfh),JSON.toJSONString(list),r);
        }

        return r.isOk();
    }


    /**
     * 删除销售发货
     */
    public boolean deleteOrder(OracleEntity.DeleteOrder info,boolean saveErrorRecord) {
        log.info("====接收到的作废发货单接口数据====,{}", JSON.toJSONString(info));
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.cancelSaleLade, JSON.toJSONString(info));
        if(r.isOk()){
            flagSyncFalse(CarbonBaseConstant.订单记录_ddjl,OrderHWANE16677Item.基本属性组_是否同步,info.getEhId());
        }

        if(saveErrorRecord){
            saveErrorRecord(info.getSalesNum(),String.valueOf(CarbonEnumKeyValue.调用接口_删除销售发货_scxsfh),JSON.toJSONString(info),r);
        }
        return r.isOk();
    }

    /**
     * 添加收款单
     */
    public boolean saveRecharge(List<OracleEntity.Recharge> list,boolean saveErrorRecord) {
        log.info("====获取到的推送收款单数据===={}",JSON.toJSONString(list));
        for (OracleEntity.Recharge recharge : list) {
            recharge.setSubsidiaryNo(PublicConstant.subsidiaryNo);
        }
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.pushSaleReceivable, JSON.toJSONString(list));

        if(r.isOk()){
            for (OracleEntity.Recharge info : list) {
                if(info.getAmount().contains(PublicConstant.HORIZONTAL)){
                    flagSyncTrue(CarbonBaseConstant.充值记录_czjl,RechargeHWANE16698Item.基本属性组_作废同步,info.getEhId());
                }else {
                    flagSyncTrue(CarbonBaseConstant.充值记录_czjl,RechargeHWANE16698Item.基本属性组_是否同步,info.getEhId());
                }
            }
        }

        if(saveErrorRecord){
            saveErrorRecord(!list.isEmpty()?list.get(0).getDocumentNo():null,String.valueOf(CarbonEnumKeyValue.调用接口_发送充值信息_fsczxx),JSON.toJSONString(list),r);
        }
        return r.isOk();
    }

    /**
     * 添加收款单 不修改
     */
    public boolean saveRechargeNoUpdate(List<OracleEntity.Recharge> list,boolean saveErrorRecord) {
        log.info("====获取到的推送删除收款单数据===={}",JSON.toJSONString(list));
        for (OracleEntity.Recharge recharge : list) {
            recharge.setSubsidiaryNo(PublicConstant.subsidiaryNo);
        }
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.pushSaleReceivable, JSON.toJSONString(list));
        if(saveErrorRecord){
            saveErrorRecord(!list.isEmpty()?list.get(0).getDocumentNo():null,String.valueOf(CarbonEnumKeyValue.调用接口_发送充值信息_fsczxx),JSON.toJSONString(list),r);
        }
        return r.isOk();
    }

    /**
     * 提货点接口
     */
    public boolean savePickup(List<OracleEntity.Pickup> list,boolean saveErrorRecord) {
        log.info("====获取到的推送提货点接口===={}",JSON.toJSONString(list));
        for (OracleEntity.Pickup recharge : list) {
            recharge.setSiCode(PublicConstant.subsidiaryNo);
        }
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.pushCompanyProductUrl, JSON.toJSONString(list));
        if(r.isOk()){
            for (OracleEntity.Pickup info : list) {
                flagSyncTrue(CarbonBaseConstant.提货点_thd,PickupPointHWANE17409Item.基本属性组_是否同步,info.getEhId());
            }
        }

        if(saveErrorRecord){
            saveErrorRecord(!list.isEmpty()?list.get(0).getSubareaName():null,String.valueOf(CarbonEnumKeyValue.调用接口_发送提货点信息_fsthdxx),JSON.toJSONString(list),r);
        }
        return r.isOk();
    }
    private void flagSyncTrue(String base,String itemSync,String id){
        IntegrationMsg msg=CarbonPanel.getFGRecordBuilder(base,id)
                .putAttribute(itemSync,true)
                .integrate();
        log.info("{}同步成功标记为true 是否成功{}",id,msg.success());
    }
    private void flagSyncFalse(String base,String itemSync,String id){
        IntegrationMsg msg=CarbonPanel.getFGRecordBuilder(base,id)
                .putAttribute(itemSync,false)
                .integrate();
        log.info("{}同步成功标记为false 是否成功{}",id,msg.success());
    }

    /**
     * 获取汇率
     */
    public BigDecimal getRate(OracleEntity.Parameter info) {
        info.setSiCode(PublicConstant.subsidiaryNo);
        OracleEntity.ReturnData r = sendGetDataRequestString(LwdHttpConfig.exchangeRate, JSON.toJSONString(info));
        if(r.isOk()){
            List<OracleEntity.Rate> list=JSON.parseArray(JSON.toJSONString(r.getData().get("data")),OracleEntity.Rate.class);
            if(list!=null&&!list.isEmpty()){
                // 取最晚生效的汇率
                return new BigDecimal(list.stream().max(Comparator.comparing(OracleEntity.Rate::getEffectiveDate)).get().getExchangeRate());
            }
        }
        return null;
    }

    public OracleEntity.ReturnData sendGetDataRequestString(String url, String json){
        log.info("开始提交数据接口：{} \n参数{}", url,json);
        HttpResponse httpResponse;
        OracleEntity.ReturnData data=new OracleEntity.ReturnData();
        data.setOk(false);
        try {
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
            String nonce = RandomStringUtils.randomAlphanumeric(11);
            OAuthRequest request = new OAuthRequest(Verb.POST, url);
            request.setRealm(LwdHttpConfig.realm);
            request.addHeader("Content-Type", "application/json");
            request.addPayload(json);
            request.addOAuthParameter("oauth_consumer_key", LwdHttpConfig.consumerKey);
            request.addOAuthParameter("oauth_token", LwdHttpConfig.accessToken);
            request.addOAuthParameter("oauth_signature_method", "HMAC-SHA256");
            request.addOAuthParameter("oauth_timestamp", timestamp);
            request.addOAuthParameter("oauth_nonce", nonce);
            request.addOAuthParameter("oauth_version", "1.0");
            String headerFormat = "OAuth realm=\"" + LwdHttpConfig.realm + "\",oauth_consumer_key=\"" + LwdHttpConfig.consumerKey + "\"," +
                    "oauth_token=\"" + LwdHttpConfig.accessToken + "\"," +
                    "oauth_signature_method=\"HMAC-SHA256\",oauth_timestamp=\"" + timestamp
                    + "\",oauth_nonce=\"" + nonce + "\",oauth_version=\"1.0\"," +
                    "oauth_signature=\"" + hmacExampleUtils.getMima(request, LwdHttpConfig.consumerSecret, LwdHttpConfig.tokenSecret) + "\"";
            httpResponse = HttpRequest.post(url).body(json).header(Header.AUTHORIZATION, headerFormat).execute();
            String response = httpResponse.body();
            log.info("提交接口状态返回：{}\n接口返回：{}", httpResponse.getStatus(),response);
            if (httpResponse.getStatus() == HttpStatus.HTTP_OK) {
                data.setData(JSONObject.parseObject(response));
                if(data.getData().get("status").equals("S")){
                    data.setOk(true);
                    return data;
                }
            }
            log.info("调取接口失败");
            return data;
        } catch (Exception ex) {
            log.info("调取接口异常");
            return data;
        }
    }

    /**
     * 添加异常记录
     */
    public void saveErrorRecord(String name,String type,String data,OracleEntity.ReturnData r){
        CarbonPanel.changeCurrentProgram(Long.valueOf(LwdHttpConfig.programCode));
        ErrorRecord errorRecord = new ErrorRecord();
        errorRecord.setDateTime(new Date());
        errorRecord.setName(name);
        errorRecord.setIsOk(r.isOk());
        errorRecord.setType(type);
        errorRecord.setData(data);
        errorRecord.setRequestResults(r.isOk()?null:JSON.toJSONString(r.getData()));
        CarbonPanel.getRecordIntegration(CarbonBaseConstant.发送记录_fsjl).integrate(errorRecord);
    }
}
